
package dialogs;

import database.COINCOMODatabaseManager;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
import javax.swing.tree.DefaultTreeModel;
import main.COINCOMO;
import main.GlobalMethods;
import main.Icons;
import panels.HierarchyPanel;
import panels.OverviewsAndGraphsPanel;

/**
 *
 * @author Raed Shomali
 */
public class ConnectDialog extends JDialog implements ActionListener , ItemListener
{
    Container c = getContentPane();

    JLabel titleLegendLabel = new JLabel( "" );

    JLabel nameLabel = new JLabel( "Name:" );

    JLabel ipAddressLabel = new JLabel( "IP Address:" );

    JLabel usernameLabel = new JLabel( "Userame:" );

    JLabel passwordLabel = new JLabel( "Password:" );

    JButton connectButton = new JButton( "Connect" );

    JButton closeButton = new JButton( "Close" );

    JTextField nameTextField = new JTextField();

    JTextField ipAddressTextField = new JTextField();

    JTextField portTextField = new JTextField();

    JTextField usernameTextField = new JTextField();

    JPasswordField passwordField = new JPasswordField();

    JRadioButton postgresRadio = new JRadioButton( "Postgres" , true );

    JRadioButton mySQLRadio = new JRadioButton( "MySQL" );

    JRadioButton defaultPortRadio = new JRadioButton( "Default Port" , true );

    JRadioButton portRadio = new JRadioButton( "Port" );

    /**
     * 
     * @param parentFrame is the original frame that generated this Dialog
     */
    public ConnectDialog( JFrame parentFrame )
    {
        super( parentFrame );

        this.setTitle( "Connect..." );
        this.setModal( true );

        // Labels
        nameLabel.setFont( new Font( "arial" , 1 , 11 ) ) ;
        ipAddressLabel.setFont( new Font( "arial" , 1 , 11 ) ) ;
        usernameLabel.setFont( new Font( "arial" , 1 , 11 ) ) ;
        passwordLabel.setFont( new Font( "arial" , 1 , 11 ) ) ;
        
        // Defaults ...
        nameTextField.setText( COINCOMODatabaseManager.DB_NAME );
        ipAddressTextField.setText( COINCOMODatabaseManager.HOST );
        portTextField.setText( COINCOMODatabaseManager.PORT );
        usernameTextField.setText( COINCOMODatabaseManager.USERNAME );
        passwordField.setText( COINCOMODatabaseManager.PASSWORD );

        // Texts Fields
        portTextField.setEnabled( false );

        nameTextField.setFont( new Font( "courier" , 0 , 12 ) );
        ipAddressTextField.setFont( new Font( "courier" , 0 , 12 ) );
        portTextField.setFont( new Font( "courier" , 0 , 12 ) );
        usernameTextField.setFont( new Font( "courier" , 0 , 12 ) );
        passwordField.setFont( new Font( "courier" , 0 , 12 ) );

        // Buttons
        connectButton.addActionListener( this );
        closeButton.addActionListener( this );

        connectButton.setIcon( Icons.CONNECT_ICON );
        closeButton.setIcon( Icons.CLOSE_ICON );

        connectButton.setFocusable( false ) ;
        closeButton.setFocusable( false ) ;

        // Radio Buttons & Groups
        defaultPortRadio.addItemListener( this );
        portRadio.addItemListener( this );

        ButtonGroup databaseButtonGroup = new ButtonGroup();
        databaseButtonGroup.add( postgresRadio );
        databaseButtonGroup.add( mySQLRadio );

        ButtonGroup portButtonGroup = new ButtonGroup();
        portButtonGroup.add( defaultPortRadio );
        portButtonGroup.add( portRadio );

        // Legend
        TitledBorder legendTitleBorder = BorderFactory.createTitledBorder( "Site Parameters" );
        legendTitleBorder.setTitleColor( Color.BLUE );
        titleLegendLabel.setBorder( legendTitleBorder );

        GlobalMethods.updateStatusBar( "Done." );

        // GUI
        c.setLayout( null );

        c.add( titleLegendLabel );

        c.add( nameLabel );
        c.add( ipAddressLabel );
        c.add( usernameLabel );
        c.add( passwordLabel );

        c.add( nameTextField );
        c.add( ipAddressTextField );
        c.add( portTextField );
        c.add( usernameTextField );
        c.add( passwordField );

        c.add( postgresRadio );
        c.add( mySQLRadio );
        c.add( defaultPortRadio );
        c.add( portRadio );

        c.add( connectButton );
        c.add( closeButton );

        titleLegendLabel.setBounds( 20 , 10 , 260 , 290 );

        nameLabel.setBounds( 40 , 35 , 100 , 22 );
        nameTextField.setBounds( 40 , 55 , 220 , 22 );
        ipAddressLabel.setBounds( 40 , 85 , 100 , 22 );
        ipAddressTextField.setBounds( 40 , 105 , 220 , 22 );

        postgresRadio.setBounds( 40 , 135 , 100 , 22 );
        mySQLRadio.setBounds( 140 , 135 , 100 , 22 );
        defaultPortRadio.setBounds( 40 , 165 , 100 , 22 );
        portRadio.setBounds( 40 , 190 , 50 , 22 );
        portTextField.setBounds( 110 , 190 , 60 , 22 );

        usernameLabel.setBounds( 40 , 230 , 70 , 22 );
        passwordLabel.setBounds( 40 , 260 , 70 , 22 );
        usernameTextField.setBounds( 110 , 230 , 150 , 22 );
        passwordField.setBounds( 110 , 260 , 150 , 22 );

        connectButton.setBounds( 30 , 310 , 110 , 25 );
        closeButton.setBounds( 160 , 310 , 110 , 25 );

        this.setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
        this.setLocation( this.getOwner().getX() + 100 , this.getOwner().getY() + 100 );
        this.setResizable( false );
        this.setSize( 305 , 380 );
        this.setVisible( true );
    }

    public void actionPerformed( ActionEvent e )
    {
        if ( e.getSource() == connectButton )
        {
            // Validations ...
            if ( nameTextField.getText().isEmpty() )
            {
                GlobalMethods.updateStatusBar( "Database Name Can NOT be Empty !" , Color.RED );

                return;
            }
            else if ( ipAddressTextField.getText().isEmpty() )
            {
                GlobalMethods.updateStatusBar( "IP Address Can NOT Be Empty !" , Color.RED );

                return;
            }
            else if ( portTextField.getText().isEmpty() && portRadio.isSelected() )
            {
                GlobalMethods.updateStatusBar( "Port Can NOT Be Empty !" , Color.RED );

                return;
            }

            // Disable the Buttons (Give Loading Effect)
            connectButton.setEnabled( false );
            closeButton.setEnabled( false );

            GlobalMethods.updateStatusBar( "Connecting ..." );

            final JDialog currentDialog = this;

            SwingUtilities.invokeLater( new Runnable()
            {
                public void run()
                {
                    COINCOMODatabaseManager.DB_NAME = nameTextField.getText();
                    COINCOMODatabaseManager.DB_DRIVER = postgresRadio.isSelected() ? COINCOMODatabaseManager.POSTGRES_DRIVER : COINCOMODatabaseManager.MYSQL_DRIVER;
                    COINCOMODatabaseManager.DB_TYPE = postgresRadio.isSelected() ? COINCOMODatabaseManager.POSTGRES_TYPE : COINCOMODatabaseManager.MYSQL_TYPE;
                    COINCOMODatabaseManager.HOST = ipAddressTextField.getText();
                    COINCOMODatabaseManager.PORT = postgresRadio.isSelected() ? COINCOMODatabaseManager.POSTGRES_PORT : COINCOMODatabaseManager.MYSQL_PORT;
                    COINCOMODatabaseManager.PORT = defaultPortRadio.isSelected() ? COINCOMODatabaseManager.PORT : portTextField.getText();
                    COINCOMODatabaseManager.USERNAME = usernameTextField.getText();
                    COINCOMODatabaseManager.PASSWORD = String.valueOf( passwordField.getPassword() );

                    // Is registering successful ?
                    if ( COINCOMODatabaseManager.registerDriver() )
                    {
                        // Can we create a connection ?
                        if ( COINCOMODatabaseManager.getConnection() != null )
                        {
                            COINCOMO.disconnectDatabaseMenuItem.setEnabled( true );

                            COINCOMO.newProjectMenuItem.setEnabled( true );
                            COINCOMO.viewProjectsMenuItem.setEnabled( true );
                            COINCOMO.viewCotsProjectsMenuItem.setEnabled( true );
                            COINCOMO.exportProjectMenuItem.setEnabled( true );

                            COINCOMO.effortAdjustmentFactorsMenuItem.setEnabled( true );
                            COINCOMO.scaleFactorsMenuItem.setEnabled( true );
                            COINCOMO.equationEditorMenuItem.setEnabled( true );
                            COINCOMO.functionPointsMenuItem.setEnabled( true );
                            COINCOMO.personMonthMenuItem.setEnabled( true );

                            DefaultTreeModel model = (DefaultTreeModel) HierarchyPanel.tree.getModel();
                            model.setRoot( null );

                            HierarchyPanel.tree.setEnabled( true );

                            HierarchyPanel.addSubSystemButton.setEnabled( false );
                            HierarchyPanel.addComponentButton.setEnabled( false );
                            HierarchyPanel.deleteSubSystemButton.setEnabled( false );
                            HierarchyPanel.deleteComponentButton.setEnabled( false );

                            OverviewsAndGraphsPanel.tabs.setEnabled( true );

                            // Clear COPSEMO
                            OverviewsAndGraphsPanel.tabs.setEnabledAt( 1 , false );
                            OverviewsAndGraphsPanel.tabs.setComponentAt( 1 ,  new JPanel() );
        
                            // If Tabs Exist ...
                            if ( OverviewsAndGraphsPanel.tabs.getTabCount() > 0 )
                            {
                                OverviewsAndGraphsPanel.clearOverviewTab();
                            }

                            GlobalMethods.updateStatusBar( "Connected to Database." );

                            // Close Window
                            currentDialog.dispose();
                        }
                    }
                    else
                    {
                        GlobalMethods.updateStatusBar( "Could Not Register Database Driver." , Color.RED );
                    }

                    // Set Back to Default
                    connectButton.setEnabled( true );
                    closeButton.setEnabled( true );
                }

            } );
        }
        else
        {
            // Exit ...
            this.dispose();
        }
    }

    public void itemStateChanged( ItemEvent e )
    {
        // Only Check Items When Selected ...
        if ( e.getStateChange() == ItemEvent.SELECTED )
        {
            // Set to Default
            portTextField.setEnabled( false );

            if ( e.getSource() == portRadio )
            {
                // Set to Enabled when Custom Port Radio Is selected
                portTextField.setEnabled( true );
            }
        }
    }

}
